#!/usr/bin/python
# -*- coding: UTF-8 -*-

from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.db import transaction, IntegrityError
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.utils.decorators import method_decorator
from django.views import generic
from conversejs.models import XMPPAccount
from get_friends import RosterBrowser

# Create your views here.
from hqz import logger
from hqz.constants import MAIL_OCCUPIED, REGISTER_CODE_TIMES_INVALID, REGISTER_CODE_NOT_EXIST, INTEGRITY_ERROR
from hqz.models import AppUserDetail, SchoolCoterie,Activity
from hqzauth import AppUser


class IndexView(generic.ListView):
    template_name = 'hqz/index.html'
    context_object_name = 'main_list'

    def get_queryset(self):
        return []

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(IndexView, self).dispatch(*args, **kwargs)


def index(request):
    """
    Index
    """
    return render(request, 'hqz/index.html')


class LoginView(generic.DetailView):
    """
    Login view after registration
    """
    model = AppUser
    template_name = 'hqz/login.html'


def register(request):
    """
    Register new user.
    """
    nickname = request.POST['nickname']
    email = request.POST['email']
    register_code = request.POST['register_code']
    password = request.POST['reg_password']
    sex = request.POST['sex']
    if len(AppUser.objects.filter(email__exact=email)) > 0:
        logger.warn('The mail: {0} has been registered'.format(email))
        return render(request, 'hqz/index.html', {
            'error_message': MAIL_OCCUPIED.format(email),
        })
    if 'male' == sex:
        transformed_sex = True
    elif 'female' == sex:
        transformed_sex = False
    try:
        school_coterie = SchoolCoterie.objects.get(pk=register_code)
        count = len(AppUserDetail.objects.filter(school_coterie__exact=school_coterie))
        if count > 0:
            logger.info('The code %s has been registered for %d times.' % (register_code, count))
            if school_coterie.code.times > 0:
                school_coterie.code.times -= 1
                app_user = AppUser.objects.create_user(email, nickname, transformed_sex, register_code, password)
            else:
                logger.warn('The register code: {0} use times passed'.format(register_code))
                return render(request, 'hqz/index.html', {
                    'error_message': REGISTER_CODE_TIMES_INVALID.format(register_code), })
        else:
            if school_coterie.code.times > 0:
                school_coterie.code.times -= 1
            app_user = AppUser.objects.create_user(email, nickname, transformed_sex, register_code, password)
    except SchoolCoterie.DoesNotExist:
        logger.warn('The register code: {0} does not exist!'.format(register_code))
        return render(request, 'hqz/index.html', {
            'error_message': REGISTER_CODE_NOT_EXIST.format(register_code),
        })
    else:
        try:
            with transaction.atomic():
                school_coterie.code.save()
                app_user.save()
                app_user_detail = AppUserDetail()
                app_user_detail.school_coterie = school_coterie
                app_user_detail.app_user = app_user
                app_user_detail.save()
        except IntegrityError:
            return render(request, 'hqz/index.html', {
                'app_user': app_user,
                'error_message': INTEGRITY_ERROR,
            })
        return HttpResponseRedirect(reverse('hqz:loginreg', args=(app_user.id,)))


def login(request):
    """
    Login
    """
    return render(request, 'hqz/login.html')


@login_required
def main(request):
    """
    Main page
    """
    active_list = Activity.objects.order_by('-start_time')[:5]
    user = request.user;
    xmpp_account = XMPPAccount.objects.get(user=user.pk)
    parsed_username = user.get_username().replace('@', '.')
    logger.warn('parsed name : {0} !'.format(parsed_username))
    xmpp_jid = parsed_username + u'@' + '127.0.0.1'
    xmpp = RosterBrowser(xmpp_jid, xmpp_account.password)
    if xmpp.connect():
        xmpp.process(block=True)
    xmpp.process(block=True)
    logger.warn('friends name : {0} !'.format(xmpp.friends))
    return render(request, 'hqz/main.html',  {
                    'active_list': active_list,'friend_list':xmpp.friends, })


@login_required
def sample(request):
    """
    Only a sample
    """
    return render(request, 'hqz/sample.html')


@login_required
def sample2(request):
    """
    Only a sample
    """
    return render(request, 'hqz/sample2.html')